// stores/reconciliationStore.ts
import { defineStore } from 'pinia'
import { reconciliationAPI } from '@/api/reconciliation'
import { getTransactions } from '@/api/transaction'
import { getSalesOrders } from '@/api/sales'
import type { Transaction, SalesOrder, MatchResult } from '@/types/workbench'
import type { ReconciliationResult } from '@/types/reconciliation'

// 定义状态类型
interface WorkbenchState {
  pendingTransactions: Transaction[]
  pendingOrders: SalesOrder[]
  matchResults: MatchResult[]
  selectedTransactions: Transaction[]
  selectedOrders: SalesOrder[]
  confirmedMatches: ReconciliationResult[]
  workbenchStats: {
    pendingTransactions: number
    pendingOrders: number
    matchedCount: number
    confirmedCount: number
    successRate: number
  }
  currentAlgorithm: string
  matchingStatus: 'idle' | 'matching' | 'success' | 'error'
  loading: boolean
}

export const useReconciliationStore = defineStore('reconciliation', {
  state: () => ({
    pendingTransactions: [] as Transaction[],
    pendingOrders: [] as SalesOrder[],
    matchResults: [] as MatchResult[],
    selectedTransactions: [] as Transaction[],
    selectedOrders: [] as SalesOrder[],
    confirmedMatches: [] as ReconciliationResult[],
    workbenchStats: {
      pendingTransactions: 0,
      pendingOrders: 0,
      matchedCount: 0,
      confirmedCount: 0,
      successRate: 0
    },
    currentAlgorithm: 'comprehensive',
    matchingStatus: 'idle' as 'idle' | 'matching' | 'success' | 'error',
    loading: false
  }),

  getters: {
    highConfidenceMatches: (state: WorkbenchState) => 
      state.matchResults.filter((item: MatchResult) => item.confidence >= 80),
    
    needsReviewMatches: (state: WorkbenchState) =>
      state.matchResults.filter((item: MatchResult) => item.confidence < 80 && item.confidence >= 50),
    
    canAutoMatch: (state: WorkbenchState) => 
      state.selectedTransactions.length > 0 && state.selectedOrders.length > 0
  },

  actions: {
    setSelectedTransactions(transactions: Transaction[]) {
      this.selectedTransactions = transactions
    },
    
    setSelectedOrders(orders: SalesOrder[]) {
      this.selectedOrders = orders
    },
    
    setCurrentAlgorithm(algorithm: string) {
      this.currentAlgorithm = algorithm
    },
    
    async loadPendingTransactions() {
      this.loading = true
      try {
        const response = await getTransactions({
          pageSize: 100, // 获取更多数据用于测试
          transactionType: 'income' // 只获取收入类型的银行流水
        })
        console.log('银行流水API响应:', response);
        
        // 添加更完善的错误检查
        if (!response || !response.data) {
          console.error('银行流水API返回数据格式错误:', response)
          throw new Error('银行流水API返回数据格式错误')
        }
        
        // 处理分页数据格式
        let transactions = []
        if (Array.isArray(response.data)) {
          transactions = response.data
        } else if (response.data.list && Array.isArray(response.data.list)) {
          transactions = response.data.list
        } else {
          console.error('银行流水数据格式不正确:', response.data)
          transactions = []
        }
        
        // 转换数据格式以匹配前端类型
        this.pendingTransactions = transactions.map((item: any) => ({
          id: item.id?.toString() || '',
          transactionId: item.transactionId || item.transaction_id || '',
          payerName: item.payerName || item.payer_name || '',
          amount: typeof item.amount === 'string' ? parseFloat(item.amount) : item.amount || 0,
          transactionDate: item.transactionDate || item.transaction_date || '',
          transactionTime: item.transactionTime || item.transaction_time || '',
          remark: item.remark || '',
          isFiltered: item.isFiltered || item.is_filtered || false,
          dataSource: item.dataSource || item.data_source || 'file_import'
        }))
        
        // 更新统计信息
        this.workbenchStats.pendingTransactions = this.pendingTransactions.length
      } catch (error) {
        console.error('加载银行流水数据失败:', error)
        this.pendingTransactions = [] // 设置为空数组防止后续错误
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async loadPendingOrders() {
      this.loading = true
      try {
        const response = await getSalesOrders({
          page: 1,
          limit: 100, // 获取100条数据用于对账
          orderStatus: 'completed' // 只获取已完成的订单
        })
        
        // 添加更完善的错误检查
        if (!response || !response.list) {
          console.error('销售订单API返回数据格式错误:', response)
          throw new Error('销售订单API返回数据格式错误')
        }
        
        // 处理分页数据格式
        let orders: any[] = []
        if (Array.isArray(response.list)) {
          orders = response.list
        } else {
          console.error('销售订单数据格式不正确:', response)
          orders = []
        }
        
        // 转换数据格式以匹配前端类型
        this.pendingOrders = orders.map((item: any) => ({
          id: item.id?.toString() || '',
          platformOrderId: item.platformOrderId || item.platform_order_id || '',
          customerName: item.customer?.name || item.customerName || item.customer_name || '',
          amount: typeof item.orderAmount === 'string' ? parseFloat(item.orderAmount) : (item.orderAmount || 0),
          orderDate: item.orderDate || item.order_date || '',
          orderStatus: item.orderStatus || item.order_status || 'completed',
          invoiceStatus: item.invoiceStatus || item.invoice_status || 'uninvoiced',
          platformSource: item.platformSource || item.platform_source || 'zcy'
        }))
        
        // 更新统计信息
        this.workbenchStats.pendingOrders = this.pendingOrders.length
      } catch (error) {
        console.error('加载销售订单数据失败:', error)
        this.pendingOrders = [] // 设置为空数组防止后续错误
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async loadPendingData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadPendingTransactions(),
          this.loadPendingOrders()
        ])
      } catch (error) {
        console.error('加载数据失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    async smartMatch(algorithm = 'comprehensive', onProgress?: (progress: number) => void) {
      this.loading = true
      this.matchingStatus = 'matching'
      try {
        // 调用真实的智能匹配API
        const result = await reconciliationAPI.smartMatch(algorithm, {
          confidence_threshold: 50,
          time_range_days: 30,
          enable_fuzzy_match: true
        })
        
        console.log('API返回的原始数据:', result);
        
        // 检查返回的数据结构
        if (!result) {
          throw new Error('API返回的数据为空');
        }
        
        // 添加更完善的匹配结果检查
        let matches = []
        if (Array.isArray(result)) {
          matches = result
        } else if (result.data && result.data.list && Array.isArray(result.data.list)) {
          matches = result.data.list
        } else {
          console.error('匹配结果数据格式不正确:', result)
          throw new Error('API返回的matches字段不是数组')
        }
        
        // 转换匹配结果格式
        const results: MatchResult[] = matches.map((match: any) => {
          // 确保salesOrder和bankTransaction存在
          const salesOrder = match.salesOrder || match.sales_order || {}
          const bankTransaction = match.bankTransaction || match.bank_transaction || {}
          
          return {
            id: match.id?.toString() || `${salesOrder.id}-${bankTransaction.id}`,
            salesOrder: {
              id: (salesOrder.id || '').toString(),
              platformOrderId: salesOrder.platformOrderId || salesOrder.platform_order_id || '',
              customerName: salesOrder.customer?.name || salesOrder.customerName || salesOrder.customer_name || '',
              amount: typeof salesOrder.orderAmount === 'string' ? parseFloat(salesOrder.orderAmount) : (salesOrder.orderAmount || 0),
              orderDate: salesOrder.orderDate || salesOrder.order_date || '',
              orderStatus: salesOrder.orderStatus || salesOrder.order_status || 'completed',
              invoiceStatus: salesOrder.invoiceStatus || salesOrder.invoice_status || 'uninvoiced',
              platformSource: salesOrder.platformSource || salesOrder.platform_source || 'zcy'
            },
            bankTransaction: {
              id: (bankTransaction.id || '').toString(),
              transactionId: bankTransaction.transactionId || bankTransaction.transaction_id || '',
              payerName: bankTransaction.payerName || bankTransaction.payer_name || '',
              amount: typeof bankTransaction.amount === 'string' ? parseFloat(bankTransaction.amount) : (bankTransaction.amount || 0),
              transactionDate: bankTransaction.transactionDate || bankTransaction.transaction_date || '',
              transactionTime: bankTransaction.transactionTime || bankTransaction.transaction_time || '',
              remark: bankTransaction.remark || '',
              isFiltered: bankTransaction.isFiltered || bankTransaction.is_filtered || false,
              dataSource: bankTransaction.dataSource || bankTransaction.data_source || 'file_import'
            },
            matchType: match.matchType || match.match_type || 'auto',
            matchAlgorithm: match.algorithmUsed || match.algorithm_used || match.matchAlgorithm || match.match_algorithm || algorithm,
            confidence: match.matchConfidence !== undefined ? 
              (typeof match.matchConfidence === 'string' ? parseFloat(match.matchConfidence) : match.matchConfidence) : 
              (match.match_confidence || 0),
            matchStatus: match.matchStatus || match.match_status || 'pending',
            matchedAt: match.matchedAt || match.matched_at || new Date().toISOString(),
            reasoning: {
              factors: Array.isArray(match.reasoning) ? match.reasoning.map((factor: any) => ({
                factor: factor.factor || '',
                score: factor.score || 0,
                weight: factor.weight || 0,
                description: factor.description || ''
              })) : [],
              totalScore: match.matchConfidence || match.match_confidence || 0
            }
          }
        })
        
        this.matchResults = results
        this.matchingStatus = 'success'
        
        // 更新统计信息
        this.workbenchStats.matchedCount = results.length
        
        return results
      } catch (error) {
        console.error('智能匹配失败:', error)
        this.matchingStatus = 'error'
        this.matchResults = [] // 清空匹配结果防止后续错误
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async manualMatch() {
      this.loading = true
      try {
        // 确保有选中的交易和订单
        if (this.selectedTransactions.length === 0 || this.selectedOrders.length === 0) {
          throw new Error('请先选择要匹配的交易和订单')
        }
        
        // 调用API进行手动匹配
        const result = await reconciliationAPI.manualMatch(
          this.selectedTransactions.map(t => t.id),
          this.selectedOrders.map(o => o.id)
        )
        
        if (result.success) {
          // 更新匹配结果
          this.matchResults = result.data.list
          
          // 重新加载待匹配数据
          await this.loadPendingData()
          
          return result
        } else {
          throw new Error(result.message || '手动匹配失败')
        }
      } catch (error) {
        console.error('手动匹配失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async confirmMatch(id: string) {
      this.loading = true
      try {
        const result = await reconciliationAPI.confirmMatch(id)
        
        if (result.success) {
          // 更新匹配结果状态
          const index = this.matchResults.findIndex(match => match.id === id)
          if (index !== -1 && this.matchResults[index]) {
            this.matchResults[index].matchStatus = 'confirmed'
          }
          
          // 更新统计信息
          this.workbenchStats.confirmedCount++
          
          return result
        } else {
          throw new Error(result.message || '确认匹配失败')
        }
      } catch (error) {
        console.error('确认匹配失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async rejectMatch(id: string) {
      this.loading = true
      try {
        const result = await reconciliationAPI.rejectMatch(id)
        
        if (result.success) {
          // 从匹配结果中移除
          this.matchResults = this.matchResults.filter(match => match.id !== id)
          
          // 重新加载待匹配数据
          await this.loadPendingData()
          
          return result
        } else {
          throw new Error(result.message || '拒绝匹配失败')
        }
      } catch (error) {
        console.error('拒绝匹配失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async loadReconciliationStats() {
      this.loading = true
      try {
        const result = await reconciliationAPI.getReconciliationStats()
        
        if (result.success) {
          // 更新统计信息
          this.workbenchStats = {
            ...this.workbenchStats,
            ...result.data
          }
          
          return result
        } else {
          throw new Error(result.message || '获取对账统计信息失败')
        }
      } catch (error) {
        console.error('获取对账统计信息失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    }
  }
})